<template>
  <view class="container" :style="{backgroundImage: `url(${staticImgs.bg})`}">
    <view class="box">
      <view v-if="step === 1">
        <view class="input-box">
          <view class="input-row">
            <view class="input-title">您希望如何被称呼</view>
            <input class="input flex-vc" placeholder="请输入" placeholder-style="color: #9E8663;" v-model="form.userName" :maxlength="20" />
          </view>
          <view class="input-row">
            <view class="input-title">您的联系方式</view>
            <input class="input flex-vc" placeholder="请输入" placeholder-style="color: #9E8663;" v-model="form.phone" :maxlength="20" />
          </view>
        </view>
        <button class="submit-btn flex-cc" @click="nextStep">确定</button>
        <view class="tip">为了方便我们及时联系到您，请填写真实信息。</view>
      </view>
      <template v-else-if="step === 2">
        <view class="box-main">
          <view class="title">亲爱的{{form.userName}}：</view>
          <view class="tip">您的专属顾问会在您方便的时候联系您，和您沟通后，指派最适合您的心理老师。</view>
          <view class="radio-box flex-vc">
            <view :class="['radio-item', 'flex-vc', {selected: form.receptionTimeRadio === 1}]" @click="form.receptionTimeRadio = 1">
              <view class="radio flex-cc" />
              <view class="radio-text">尽快联系我{{timeText}}</view>
            </view>
            <view :class="['radio-item', 'flex-vc', {selected: form.receptionTimeRadio === 2}]" @click="form.receptionTimeRadio = 2">
              <view class="radio flex-cc" />
              <view class="radio-text">指定日期</view>
            </view>
          </view>
          <template v-if="form.receptionTimeRadio === 2">
            <view class="bold-tip">何时方便联系您？</view>
            <view class="date-input-row">
              <view
                @click="showDatetimePicker"
                :class="['input', 'flex-vc', {'input-placeholder': !form.receptionTimeStr}]"
              >
                {{form.receptionTimeStr || '日期时间选择'}}
              </view>
              <image :src="staticImgs.date" class="date-img" @click="showDatetimePicker" />
            </view>
          </template>
        </view>
        <button class="submit-btn flex-cc" @click="nextStep">确定</button>
      </template>
      <view class="submit-bg" v-else-if="step === 3" :style="{backgroundImage: `url(${staticImgs.submitBg})`}">
        <view class="submit-title">您已成功提交</view>
        <view class="submit-tip">您的专属顾问会在您指定的时间尽快联系您。</view>
        <view class="center-tip">若有其他疑问，可以联系我们的客服</view>
        <button class="submit-btn flex-cc" @click="contactCustomer">联系客服</button>
      </view>
    </view>
    <datetimepicker
      :show="datePickerShow"
      v-model="datetimeValue"
      mode="datetime"
      :formatter="dateFormatter"
      @close="datePickerShow = false"
      @cancel="datePickerShow = false"
      @confirm="dateConfirm"
      :close-on-click-overlay="true"
      :min-date="minDate"
      :max-date="maxDate"
      :filter="dateFilter"
      @change="changeDate"
      :immediate-change="true"
      ref="datePicker"
    />
    <!-- 联系客服组件 -->
    <contact-pop ref='contactOursPop' is-explanation />
  </view>
</template>

<script>
import {userExplanation} from '@/common/api/user_api'
import ContactPop from '@/components/contactOursPop/contactOursPop'
import {showExplanation} from '@/common/api/scl_api'
import Datetimepicker from '@/subcontractorA/explanationOrder/components/datetimepicker/datetimepicker'

let datetimeValue

export default {
  components: {ContactPop, Datetimepicker},
  data() {
    return {
      staticImgs: {
        bg: this.imgBaseURL + '/explanation/bg.png',
        submitBg: this.imgBaseURL + '/explanation/submit.png',
        date: this.imgBaseURL + '/explanation/date.png'
      },
      form: {
        userName: '',
        phone: '',
        receptionTime: '',
        receptionTimeRadio: 1,
        receptionTimeStr: ''
      },
      step: undefined,
      datePickerShow: false,
      datetimeValue: '',
      minDate: undefined,
      maxDate: undefined,
      timeText: ''
    }
  },
  methods: {
    nextStep() {
      if (this.step === 1) {
        if (!this.form.userName) {
          this.$showToast('请输入您的称呼')
          return
        }
        if (!this.form.phone) {
          this.$showToast('请输入联系方式')
          return
        }
        this.step = 2
      } else if (this.step === 2) {
        if (this.form.receptionTimeRadio === 2 && !this.form.receptionTime) {
          this.$showToast('请输入日期时间')
          return
        }
        if (this.$dayjs(this.form.receptionTime, 'YYYY-MM-DD HH:mm:ss').isBefore(this.$dayjs())) {
          this.$showToast('停留过久，已自动调整预约时间')
          this.form.receptionTime = ''
          this.form.receptionTimeStr = ''
          this.datePickerShow = true
          return
        }
        uni.showLoading()
        userExplanation({
          userName: this.form.userName,
          phone: this.form.phone,
          receptionTime: this.form.receptionTimeRadio === 1 ? this.$dayjs().format('YYYY-MM-DD HH:mm:ss') : this.form.receptionTime
        }).then(res => {
          if (res.data.success) {
            this.step = 3
          } else {
            this.$showToast('提交失败')
          }
        }).finally(() => uni.hideLoading())
      }
    },
    contactCustomer() {
      this.$refs.contactOursPop.showPopup()
    },
    dateFormatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}点`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },
    dateConfirm({value}) {
      this.datetimeValue = value
      datetimeValue = value
      if (this.$dayjs(value).hour() === 18) {
        // 临时解决18点问题
        this.datetimeValue = this.$dayjs(value).minute(0).valueOf()
        datetimeValue = this.datetimeValue
      }
      this.form.receptionTime = this.$dayjs(this.datetimeValue).format('YYYY-MM-DD HH:mm:ss')
      this.form.receptionTimeStr = this.$dayjs(this.datetimeValue).format('M月D日 HH:mm')
      this.datePickerShow = false
    },
    showDatetimePicker() {
      this.getMinMaxDate()
      this.datePickerShow = true
      if (this.form.receptionTime) {
        this.datetimeValue = this.$dayjs(this.form.receptionTime, 'YYYY-MM-DD HH:mm:ss').valueOf()
        datetimeValue = this.datetimeValue
      }
    },
    getMinMaxDate() {
      const currentTime = this.$dayjs().millisecond(0)
      if (currentTime.isAfter(currentTime.clone().hour(17).minute(30).second(0))) {
        this.minDate = currentTime.clone().add(1, 'day').hour(9).minute(0).second(0).valueOf()
      } else if (currentTime.isBefore(currentTime.clone().hour(9).minute(0).second(0))) {
        this.minDate = currentTime.clone().hour(9).minute(0).second(0).valueOf()
      } else {
        if (currentTime.clone().minute() > 15) {
          // 防止没分钟可选
          this.minDate = currentTime.clone().add(1, 'hour').minute(0).second(0).valueOf()
        } else {
          this.minDate = currentTime.clone().add(30, 'minute').second(0).valueOf()
        }
      }
      if (!this.datetimeValue) {
        this.datetimeValue = this.minDate
        datetimeValue = this.minDate
      }
      this.maxDate = currentTime.clone().add(1, 'month').hour(18).minute(0).second(0).valueOf()
      this.getInitialTime()
    },
    dateFilter(mode, options) {
      if (mode === 'hour') {
        return options.filter(option => ['09', '10', '11', '12', '13', '14', '15', '16', '17', '18'].includes(option))
      }
      if (mode === 'minute') {
        if (this.$dayjs(datetimeValue).hour() === 18) {
          return options.filter(option => ['00'].includes(option))
        } else {
          return options.filter(option => ['00', '15', '30', '45'].includes(option))
        }
      }
      return options
    },
    changeDate({value}) {
      this.datetimeValue = value
      datetimeValue = value
    },
    getInitialTime() {
      const currentTime = this.$dayjs().millisecond(0)
      if (currentTime.isSameOrAfter(currentTime.clone().hour(17).minute(30).second(0))) {
        this.timeText = '（明早9点）'
      } else if (currentTime.isBefore(currentTime.clone().hour(8).minute(0).second(0))) {
        this.timeText = '（今早9点）'
      } else {
        this.timeText = ''
      }
    }
  },
  onLoad() {
    this.getInitialTime()
    showExplanation().then(res => {
      if (res.data.success) {
        if (res.data.data === 2) {
          this.step = 3
        } else {
          this.step = 1
        }
      }
    })
  }
}
</script>

<style scoped lang="scss">
.container {
  background: {
    size: 100% auto;
    repeat: no-repeat;
    position: center top;
  }
  position: relative;
}

.box {
  width: 624rpx;
  height: 830rpx;
  background: linear-gradient(180deg, rgba(219, 193, 158, 0.29) 0%, #FFF 100%);
  box-shadow: 0 2rpx 20rpx 0 #E7D0A4;
  border-radius: 27rpx;
  position: absolute;
  top: 27%;
  left: 0;
  right: 0;
  margin: 0 auto;
  padding: 0 62rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .box-main {
    flex: 1 0 auto;
  }
}

.input-box {
  margin-bottom: 80rpx;
}

.input-row {
  margin-top: 80rpx;

  .input-title {
    font-weight: bold;
    font-size: 32rpx;
    color: #83520E;
    line-height: 45rpx;
    margin-bottom: 24rpx;
  }
}

.input {
  height: 70rpx;
  background-color: rgba(202, 168, 115, 0.25);
  border-radius: 35rpx;
  border: 1rpx solid #A7812E;
  font-size: 32rpx;
  color: #3F2706;
  padding: 0 60rpx;
}

.input-placeholder {
  font-size: 32rpx;
  color: #9E8663;
}

.submit-btn {
  height: 80rpx;
  background: linear-gradient(to bottom, #FFFEFC, #F0B96A) center center / calc(100% - 2rpx) calc(100% - 2rpx), linear-gradient(to bottom, #F1F1F1, #F1DCAD) center center / 100% 100%;
  box-shadow: 0 5rpx 0 0 #CA8827;
  border-radius: 40rpx;
  margin-top: 50rpx;
  font-weight: bold;
  font-size: 34rpx;
  color: #875D1D;
  margin-bottom: 50rpx;
  flex: 0 0 auto;
  width: 100%;
}

.title {
  font-weight: bold;
  font-size: 40rpx;
  color: #83520E;
  line-height: 56rpx;
  margin-bottom: 27rpx;
  margin-top: 60rpx;
}

.tip {
  font-size: 28rpx;
  color: #83520E;
  line-height: 40rpx;
}

.radio-box {
  margin: 60rpx 0;
}

.radio-item {
  .radio {
    width: 26rpx;
    height: 26rpx;
    border: 2rpx solid #915E16;
    border-radius: 50%;

    &::before {
      content: "";
      width: 12rpx;
      height: 12rpx;
      background-color: #83520E;
      display: none;
      border-radius: 50%;
    }
  }

  .radio-text {
    font-weight: bold;
    font-size: 28rpx;
    color: #83520E;
    margin-left: 10rpx;
    white-space: nowrap;
  }

  &.selected {
    .radio::before {
      display: block;
    }
  }

  &:not(:last-child) {
    margin-right: 50rpx;
  }
}

.bold-tip {
  @extend .tip;
  font-weight: bold;
}

.date-input-row {
  margin: 14rpx 0 10rpx;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    width: 40rpx;
    height: 40rpx;
    top: 0;
    bottom: 0;
    right: 50rpx;
    margin: auto 0;
  }

  .date-img {
    position: absolute;
    width: 40rpx;
    height: 40rpx;
    right: 50rpx;
    top: 0;
    bottom: 0;
    margin: auto 0;
  }
}

.submit-bg {
  background-size: 100% auto;
  background-repeat: no-repeat;
  background-position: center 30rpx;
  flex: 1 0 auto;
}

.submit-title {
  @extend .title;
  text-align: center;
  margin-top: 42rpx;
  margin-bottom: 0;
}

.submit-tip {
  font-size: 34rpx;
  color: #83520E;
  line-height: 50rpx;
  margin-top: 325rpx;
}

.center-tip {
  font-size: 28rpx;
  color: #83520E;
  line-height: 50rpx;
  margin-top: 32rpx;
  margin-bottom: 10rpx;
}
</style>